import fetch from 'dva/fetch';
import localstorage from 'localStorage';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  console.log('in REQUEST 的 请求返回内容',response);
  if (response.status >= 200 && 
      response.status < 500) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */


export function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}

export function requestWithAuth(url, options){
  if (localstorage.getItem('auth') == null) return request(url, options);
  //console.log('localstorage', localstorage.getItem('auth'));
  const authstorage = JSON.parse(localstorage.getItem('auth'));
  if (typeof authstorage.token === 'undefined') return request(url, options);
  const {token} = authstorage;
  options = {...options, headers: {
    "Content-Type": "application/json",
    "authorization": "Bearer " + token
  },}
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}